package cn.vihub.filter;

import cn.vihub.utils.Result;
import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServerResponse;

/**
 * @Author: 秋晚
 * @Date: 2025/8/7 08:35
 * @Description:
 **/
//@Configuration
public class MonoFilter implements GlobalFilter {

    @Value("${mygateway.role.path}")
    private String rolePath;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //查看是否是白名单
        String[] pathList = rolePath.split(",");
        String s = request.getPath().toString();
        for (String path : pathList) {
            boolean contains = s.contains(path);
            if(contains){
                //满足白名单放行
                return chain.filter(exchange);
            }
        }

        //查看Token是否存在
        String token = request.getHeaders().getFirst("token");
        if(token==null){
            return outputJson(response,"token不能为空");
        }

        //获取token
        try {
            //解密token
            String userId = Jwts.parser().setSigningKey("128903djsjhduihas167645").parseClaimsJws(token).getBody().get("id", String.class);
            //把userId包给请求头
            ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().header("X-User-Id", userId).build();
            ServerWebExchange serverWebExchange = exchange.mutate().request(serverHttpRequest).build();

            //放行
            return chain.filter(serverWebExchange);
        }catch (Exception e){
            return outputJson(response,e.getMessage());
        }

    }

    private Mono<Void> outputJson(ServerHttpResponse response,String msg){
        //设置返回状态码
        response.setStatusCode(HttpStatus.OK);
        //设置返回头
        response.getHeaders().set("Content-json","tapplication/\\json");
        //设置返回内容
        Result<Object> objectResult = new Result<>();
        objectResult.setCode(-1);
        objectResult.setMsg(msg);
        objectResult.setData("wuwuwuwu~~~~");
        DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONBytes(objectResult));

        return response.writeWith(Mono.just(wrap));

    }
}
